from flask import Blueprint, render_template, request, g, redirect, url_for, flash
from decorators import login_required
from .froms import (QuestionForm, AnswerForm, SearchForm)
from models import (QuestionModel, AnswerModel)
from exts import db

bp = Blueprint('qa', __name__, url_prefix='/')


@bp.route('/')
def index():
    questions = QuestionModel.query.order_by(db.text('-create_time')).all()
    return render_template('index.html', questions=questions)


@bp.route('/question/publish', methods=['GET', 'POST'])
@login_required
def question_publish():
    if request.method == 'GET':
        return render_template('question_publish.html')
    else:
        question_form = QuestionForm(request.form)
        if question_form.validate():
            title = question_form.title.data
            content = question_form.content.data
            question_model = QuestionModel(title=title, content=content, author=g.user)
            db.session.add(question_model)
            db.session.commit()
            return redirect('/')
        else:
            flash('标题或内容格式错误!')
            return redirect(url_for('qa.question_publish'))


@bp.route('/question/<int:question_id>')
def question_detail(question_id):
    try:
        question = QuestionModel.query.get(question_id)
        return render_template('detail.html', question=question)
    except:
        pass


@bp.route('/answer/<int:question_id>', methods=['POST'])
@login_required
def answer(question_id):
    answer_form = AnswerForm(request.form)
    if answer_form.validate():
        content = answer_form.content.data
        answer_model = AnswerModel(content=content, author=g.user, question_id=question_id)
        db.session.add(answer_model)
        db.session.commit()
        return redirect(url_for('qa.question_detail', question_id=question_id))
    else:
        flash('表单验证失败')
        return redirect(url_for('qa.question_detail', question_id=question_id))


@bp.route('/search', methods=['POST'])
def search():
    search_form = SearchForm(request.form)
    if search_form.validate():
        keyword = search_form.keyword.data
        questions = QuestionModel.query.filter(QuestionModel.title.like('%{0}%'.format(keyword))).all()
        return render_template('index.html', questions=questions)
    else:
        return redirect('/')
